const app = getApp();
const ConfigManager = require('../../utils/configManager.js');
const IniParser = require('../../utils/iniParser.js');
const MotorParamMap = require('../../utils/motorParamMap.js');

Page({
  data: {
    mcuType: '',
    motorList: [],
    selectedMotor: null,
    loading: false,
    searchValue: '',
    filteredList: [],
    hasMotorConfig: false
  },

  onLoad() {
    this.configManager = new ConfigManager();
    this.init();
  },

  async init() {
    if (!app.data.connected || !app.data.LOGOK) {
      wx.showModal({
        title: '未连接控制器',
        content: '请先连接控制器并登录',
        confirmText: '去连接',
        success: (res) => {
          if (res.confirm) {
            wx.switchTab({ url: '/pages/index/index' });
          }
        }
      });
      return;
    }

    // 等待控制器型号
    if (!app.data.ptype) {
      wx.showLoading({ title: '读取控制器信息...' });
      
      for (let i = 0; i < 30; i++) {
        await this.sleep(100);
        if (app.data.ptype) break;
      }
      
      wx.hideLoading();
    }

    this.setData({
      mcuType: app.data.ptype || '未知'
    });

    if (!app.data.ptype) {
      wx.showToast({
        title: '无法获取控制器型号',
        icon: 'none'
      });
      return;
    }

    await this.loadMotorList();
  },

  /**
   * 加载电机列表
   */
  async loadMotorList() {
    this.setData({ loading: true });

    try {
      // 1. 获取控制器配置
      const config = await this.configManager.getControllerConfig(this.data.mcuType);
      
      if (!config || !config.motorUrl) {
        this.setData({
          loading: false,
          hasMotorConfig: false
        });
        
        wx.showModal({
          title: '提示',
          content: '该型号暂无电机配置文件',
          showCancel: false
        });
        return;
      }

      // 2. 下载电机配置文件
      wx.showLoading({ title: '下载电机列表...' });
      const tempPath = await this.configManager.downloadFile(config.motorUrl);
      
      // 3. 读取并解析INI文件
      const content = await this.configManager.readFile(tempPath, 'utf8');
      const iniData = IniParser.parse(content);
      
      // 4. 转换为列表格式
      const motorList = this.parseMotorIni(iniData);

      wx.hideLoading();

      this.setData({
        motorList: motorList,
        filteredList: motorList,
        loading: false,
        hasMotorConfig: true
      });

      console.log('[Motor] 加载成功，共', motorList.length, '种电机');

    } catch (error) {
      wx.hideLoading();
      
      this.setData({ loading: false });
      
      wx.showToast({
        title: '加载电机列表失败',
        icon: 'none'
      });
      
      console.error('[Motor] 加载失败:', error);
    }
  },

  /**
   * 解析电机INI文件
   */
  parseMotorIni(iniData) {
    const list = [];
    
    for (const [name, params] of Object.entries(iniData)) {
      const paramCount = Object.keys(params).length;
      
      list.push({
        name: name,
        code: name,
        description: `包含 ${paramCount} 个参数`,
        parameters: this.parseParameters(params),
        paramCount: paramCount
      });
    }
    
    return list;
  },

  /**
   * 解析参数
   */
  parseParameters(params) {
    const result = [];
    
    for (const [key, value] of Object.entries(params)) {
      const config = MotorParamMap.getParamConfig(key);
      
      result.push({
        paramName: key,
        rawValue: value,
        config: config,
        supported: config !== null,
        displayName: config ? config.name : key
      });
    }
    
    return result;
  },

  /**
   * 搜索电机
   */
  onSearch(e) {
    const value = e.detail.toLowerCase();
    
    if (!value) {
      this.setData({
        filteredList: this.data.motorList,
        searchValue: ''
      });
      return;
    }

    const filtered = this.data.motorList.filter(item =>
      item.name.toLowerCase().includes(value) ||
      item.code.toLowerCase().includes(value)
    );

    this.setData({
      searchValue: value,
      filteredList: filtered
    });
  },

  /**
   * 选择电机
   */
  selectMotor(e) {
    const index = e.currentTarget.dataset.index;
    const motor = this.data.filteredList[index];

    wx.showModal({
      title: '确认选择',
      content: `电机: ${motor.name}\n参数数量: ${motor.paramCount}\n\n确定应用该电机参数吗？\n\n注意：此操作将修改控制器参数！`,
      confirmColor: '#e64340',
      success: (res) => {
        if (res.confirm) {
          this.applyMotor(motor);
        }
      }
    });
  },

  /**
   * 应用电机参数
   */
  async applyMotor(motor) {
    wx.showLoading({ title: '写入参数中...', mask: true });

    try {
      let successCount = 0;
      let failCount = 0;
      let skipCount = 0;

      console.log('[Motor] 开始写入电机参数:', motor.name);

      // 过滤出支持的参数
      const supportedParams = motor.parameters.filter(p => p.supported);
      const totalCount = supportedParams.length;

      console.log('[Motor] 共', totalCount, '个参数需要写入');

      for (const param of supportedParams) {
        try {
          await this.writeParameter(param);
          successCount++;
          
          console.log('[Motor] 写入成功:', param.displayName, '=', param.rawValue);
          
          // 更新进度提示
          wx.showLoading({ 
            title: `写入中 ${successCount}/${totalCount}`,
            mask: true
          });
          
          // 延迟避免写入过快
          await this.sleep(300);
          
        } catch (error) {
          console.error('[Motor] 写入参数失败:', param.displayName, error);
          failCount++;
        }
      }

      // 统计跳过的不支持参数
      skipCount = motor.paramCount - totalCount;

      wx.hideLoading();
      
      // 触发保存到Flash
      app.data.savetirg = true;
      await this.sleep(500);
      
      wx.showModal({
        title: '设置完成',
        content: `成功: ${successCount} 个\n失败: ${failCount} 个${skipCount > 0 ? '\n跳过: ' + skipCount + ' 个' : ''}`,
        showCancel: false,
        success: () => {
          // 通知其他页面刷新
          app.data.learninitreq = 1;
          app.data.advaninitreq = 1;
        }
      });

    } catch (error) {
      wx.hideLoading();
      
      wx.showToast({
        title: '设置失败: ' + error.message,
        icon: 'none',
        duration: 3000
      });
    }
  },

  /**
   * 写入单个参数
   * @param {object} param - 参数对象
   */
  async writeParameter(param) {
    return new Promise((resolve, reject) => {
      try {
        const { paramName, rawValue, config } = param;
        
        if (!config) {
          reject(new Error('参数配置不存在'));
          return;
        }

        // 转换参数值
        const sendValue = MotorParamMap.convertValue(paramName, rawValue);
        const addr = config.index;

        console.log('[Motor] 写入:', config.name, '地址:', addr, '值:', sendValue);

        // 构造Modbus写命令 (0x10 - 写多个寄存器)
        app.data.BLE_Txbuff1[0] = 0x01;                          // 设备地址
        app.data.BLE_Txbuff1[1] = 0x10;                          // 功能码: 写多个寄存器
        app.data.BLE_Txbuff1[2] = ((addr - 2) * 2) >> 8;         // 寄存器地址高字节
        app.data.BLE_Txbuff1[3] = ((addr - 2) * 2) & 0xFF;       // 寄存器地址低字节
        app.data.BLE_Txbuff1[4] = 0x00;                          // 寄存器数量高字节
        app.data.BLE_Txbuff1[5] = 0x02;                          // 寄存器数量低字节 (2个寄存器=4字节)
        app.data.BLE_Txbuff1[6] = 0x04;                          // 字节数 (4字节)
        app.data.BLE_Txbuff1[7] = (sendValue >> 8) & 0xFF;       // 数据字节1
        app.data.BLE_Txbuff1[8] = sendValue & 0xFF;              // 数据字节2
        app.data.BLE_Txbuff1[9] = (sendValue >> 24) & 0xFF;      // 数据字节3
        app.data.BLE_Txbuff1[10] = (sendValue >> 16) & 0xFF;     // 数据字节4

        // 计算CRC16
        const crc = app.crc16(app.data.BLE_Txbuff1, 11);
        app.data.BLE_Txbuff1[11] = (crc >> 8) & 0xFF;
        app.data.BLE_Txbuff1[12] = crc & 0xFF;

        // 发送数据
        app.data.Txbuffid = 1;
        app.writeBLECharacteristicValue();

        // 等待响应
        let checkCount = 0;
        const checkInterval = setInterval(() => {
          checkCount++;

          // 检查是否收到响应
          if (app.data.Rebuffi > 0) {
            const crcCheck = app.crc16(app.data.BLE_Rebuff, app.data.Rebuffi);
            
            if (crcCheck === 0) {
              // CRC校验通过
              clearInterval(checkInterval);
              app.data.Rebuffi = 0; // 清空接收缓冲区
              resolve();
            } else {
              // CRC校验失败
              clearInterval(checkInterval);
              reject(new Error('CRC校验失败'));
            }
          }

          // 超时处理（10次 * 50ms = 500ms）
          if (checkCount >= 10) {
            clearInterval(checkInterval);
            reject(new Error('写入超时'));
          }
        }, 50);

      } catch (error) {
        reject(error);
      }
    });
  },

  /**
   * 刷新列表
   */
  onRefresh() {
    this.loadMotorList();
  },

  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
});

